import React, {Component} from 'react';

import {
    Animated,
    AppRegistry,
    DeviceEventEmitter,
    Image,
    ListView,
    Modal,
    StyleSheet,
    Switch,
    Text,
    TextInput,
    TouchableHighlight,
    TouchableOpacity,
    AsyncStorage,
    View,
} from 'react-native';
import StyleUtils from "../res/styles/StyleUtils";
import ViewUtils from "../utils/ViewUtils";
import TypeUtils from "../utils/TypeUtils";
import I18n from '../res/language/i18n/index'
import CommonUtils from "../common/CommonUtils";
import AlertDialog from "./AlertDialog";
import GoodsAndArticlePage from "../pages/common/GoodsAndArticlePage";
import IparInput from "./IparInput";
// 初始状态
let ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
});


export default class SearchView extends Component {
    constructor(props) {
        super(props);

        this.sreachValue = '';
        this.state = {
            searchData: [],
            fadeAnim: new Animated.View(0),
            isFocused: false,
            visible: this.props.visible,
            dataSource: ds,

            deleteAlertVisible: false,
        }
    }


    /**
     * 刷新props
     * @param nexProps
     */
    componentWillReceiveProps(nexProps) {
        if (nexProps.visible !== this.state.visible) {
            this.setState({
                visible: nexProps.visible,
            });
        }
    }


    componentDidMount() {
        CommonUtils.getAcyncInfo('searchData')
            .then((result) => {
                if (result) {
                    this.setState({
                        searchData: JSON.parse(result),
                        dataSource: this.state.dataSource.cloneWithRows(JSON.parse(result))
                    })
                }
            })
    }

    /**
     * 更新两个js的state
     * */
    updateState() {
        this.props.updateState(false);
    }


    /**
     * 点击（查看）
     * */
    onPress() {
        if (this.sreachValue.trim().length <= 0) return;


        let searchData = this.state.searchData;

        if (searchData === null) {
            searchData = [];
        }
        searchData.splice(0, 0, this.sreachValue);
        AsyncStorage.setItem('searchData', JSON.stringify(searchData));


        // set data
        this.setState({
            searchData: searchData,
            dataSource: ds.cloneWithRows(searchData)
        });

        this.startPage(this.sreachValue);
        this.sreachValue = '';
    }


    /**
     * start page
     */
    startPage(key) {
        //close modal
        this.props.updateState(false);

        this.props.navigator.push({
            component: GoodsAndArticlePage,
            name: 'GoodsAndArticlePage',
            params: {
                dataKey: key,
            }
        });

    }


    /**
     * 初始化list view item
     * */
    renderItem(rowData, rowID) {
        return (
            <TouchableOpacity
                onPress={() => this.startPage(rowData)}
            >
                <Text style={[StyleUtils.text, {paddingLeft: 0, color: '#4b4b4b'}]}>{rowData}</Text>
            </TouchableOpacity>
        )
    }


    /**
     * 删除搜索的数据
     * */
    deleteSearchData() {
        AsyncStorage.removeItem('searchData');
        this.setState({
            deleteAlertVisible: false,
            searchData: [],
            dataSource: ds.cloneWithRows([])
        });
    }

    render() {

        return (
            <Modal
                onRequestClose={() => this.updateState()}
                animationType={'slide'}
                transparent={true}
                visible={this.state.visible}
            >
                <View style={styles.boxStyle}>

                    {/*close btn*/}
                    {/*{ViewUtils.getImageBtnView(styles.btnStyle, require('../res/images/ic_close.png'),*/}
                    {/*[StyleUtils.tabIconSize,], () => this.updateState(), '#ececec')}*/}


                    <View style={[StyleUtils.justifySpace, {marginTop: 24}]}>

                        <IparInput
                            autoFocus={true}
                            style={{
                                flex: 1,
                                marginTop: 0
                            }}
                            onChangeText={(test) => this.sreachValue = test}
                            placeholder={I18n.t('default.childDevelopment')}/>


                        {ViewUtils.getButton(I18n.t('default.check'), () => this.onPress(), {
                            width: 100,
                        })}

                    </View>

                    <View style={[StyleUtils.justifySpace, {
                        marginTop: 20,
                        paddingBottom: 15, borderBottomWidth: 1, borderColor: '#e1e1e1'
                    }]}>
                        <Text style={[StyleUtils.text, {padding: 0}]}>{I18n.t('default.searchHistory')}</Text>

                        <TouchableOpacity
                            onPress={() => {
                                if (this.state.searchData !== null && this.state.searchData.length > 0) {
                                    this.setState({
                                        deleteAlertVisible: true,
                                    })
                                }
                            }}
                            style={{padding: 8}}
                        >
                            <Image
                                style={[{width: 16, height: 16, tintColor: '#898b8d'}]}
                                source={require('../res/images/ic_delete.png')}
                            />
                        </TouchableOpacity>
                    </View>


                    <ListView
                        style={{paddingTop: 16, flex: 1}}
                        renderRow={(rowData, sectionID, rowID) => this.renderItem(rowData, rowID)}
                        dataSource={this.state.dataSource}
                    />


                    {ViewUtils.getButton(I18n.t('default.cancel'), () => this.updateState())}

                </View>

                <AlertDialog
                    contentTv={I18n.t('default.delete')}
                    leftSts={I18n.t('default.delete')}
                    rightSts={I18n.t('default.cancel')}
                    leftBtnOnclick={() => this.deleteSearchData()}
                    visible={this.state.deleteAlertVisible}
                    requestClose={() => this.setState({
                        deleteAlertVisible: false,
                    })}/>
            </Modal>
        )
    }
}


const styles = StyleSheet.create({
    boxStyle: {
        height: '100%',
        padding: 20,
        paddingTop: TypeUtils.getPhoneType() === 'x' ? 64 : 40,
        backgroundColor: 'rgba(255, 255, 255, 0.96)',
    },
    btnStyle: {
        alignSelf: 'flex-end',
        padding: 8
    },


});